﻿/*
创建人：zhangrj
日期：2022-08-01
描述：工步报工页面js
*/
var page = {
    rootPath: getRootPath(), //网站根路径
    url: getRootPath() + "/Ashx/ContainerStepInfoWorkReportHandler.ashx", //后台处理url,
    commonUrl: getRootPath() + "/Ashx/CommonHandler.ashx", //通用方法后台路径
    //设备分页参数
    pageTotal: 0,
    pageSize: 10,
    pageNumber: 1,
    init: function () {
        page.bind();
        page.initData();
    },
    //绑定事件
    bind: function () {
        customizedEasyuiPagination('pp'); //定制化分页
        //列表加载
        $("#gdResult").datagrid({
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pageTotal,
                    pageSize: page.pageSize,
                    pageNumber: page.pageNumber
                });
                customizedEasyuiPagination('pp'); //定制化分页
            },
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
                 { field: 'MFGORDERNAME', title: '订单号', width: 120 },
                 { field: 'PRODUCTBATCH', title: '件号/批次号', width: 200 },
                 { field: 'WIPQTY', title: '在制数', width: 50 },
                 { field: 'STEPINFONAME', title: '工步', width: 100 },
                 { field: 'NOWWORKFLOWSTEPNAME', title: '工序', width: 180 },
                 { field: 'WORKFLOWSTEPNAME', title: '在制工序', width: 180 },
                 { field: 'CONTAINERTYPENAME', title: '批次类型', width: 80 },
                 { field: 'DISWORKQTY', title: '已报数', width: 50 },
                 { field: 'IsFillCheckPoint', title: '检测项录入', width: 80 },
                 { field: 'PRIORITYCODE', title: '优先级', width: 50 },
                 { field: 'PLANNEDFINISHDATE', title: '计划完成日期', width: 100, formatter: function (value, row, index) {
                     if (value !== null && value !== "") {
                         return dayjs(value).format("YYYY-MM-DD");
                     }
                 }
                 },
                  { field: 'ISHAVESURPASS', title: '超越单', width: 50 }
                ]],
            onSelect: function (rowIndex, rowData) {
                page.fillData(rowData);
            }
        });
        //子批次、单件单卡列表加载
        $("#gdChildContainerInfo").datagrid({
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
                 { field: 'CONTAINERNAME', title: '批次号', width: 180 },
                 { field: 'IsFillCheckPoint', title: '检测项录入', width: 100, hidden: true },
            //                 { field: 'PRIORITYCODE', title: '优先级', width: 50 },
            //                 { field: 'ISHAVESURPASS', title: '超越单', width: 50 },
                 {field: 'SelfCheckLossQty', title: '自检报废', width: 80, hidden: true, editor:
                 { type: 'combobox', options:
                          {
                              valueField: 'value',
                              textField: 'name',
                              data: [{ name: "是", value: "1" }, { name: "否", value: "0"}],
                              editable: false
                          }
                 }
             }
                ]]
        });
        //集件列表加载
        $("#gdCollectInfo").datagrid({
            columns: [[
                 { field: 'PRODUCTNAME', title: '零件号', width: 120 },
                 { field: 'QTYREQUIRED', title: '单台数', width: 50 },
                 { field: 'ISSUEQTY', title: '发出数', width: 50 },
                 { field: 'LOSSQTYSUM', title: '报废数', width: 50 },
                 { field: 'PRODUCTCHILDNO', title: '批次号', width: 150 },
                 { field: 'EMPLOYEENAME', title: '配套者', width: 100 },
                 { field: 'NOTE', title: '备注', width: 100 }
                ]]
        });
        //列表分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                customizedEasyuiPagination('pp'); //定制化分页
                page.clearPage(true, true, true, true, true, true);
                page.pageSize = pageSize; page.pageNumber = pageNumber;
            }
        });
        $(document).ready(function () {
            //绑定分页go按钮
            $('#pageGo').on("click", function () {
                page.clearPage(true, true, true, true, true, true);
                var pageNumber = $(this).parents('tr').find('.pagination-num').val();
                page.pageNumber = pageNumber;
            });
        });
        //刷新页面
        $("#btnReload").on("click", function () {
            window.location.reload();
        });
        //待报工勾选事件
        $("#ckCurrStep").on("change", function () {
            page.search();
        });
        //报工
        $("#btnWorkReport").on("click", function () {
            page.saveWorkReport();
        });
        //实测值录入
        $("#btnInputCheckPoint").on("click", function () {
            var row = $("#gdResult").datagrid('getChecked'); //选中的批次
            if (row.length === 0) {
                displayMessage("未选择工步", false);
                return;
            }
            if (row[0].CONTAINERTYPE === 7) {
                row = $("#gdChildContainerInfo").datagrid('getChecked'); //选中的批次
                if (row.length === 0) {
                    displayMessage("未选择单件批次", false);
                    return;
                }
            }
            page.post(page.url, { action: "SetInputCheckPoint", mainDt: JSON.stringify(row) }, true, function (res) {
                if (!res.Result) {
                    displayMessage(resData.Message, false);
                    return;
                }
                page.openStepCheckItem();
            });
        });
        //批次流水卡打印查看
        $('#btnViewContainer').on("click", function () {
            clearMessage();
            page.viewContainerPrint();
        });
        //文档查看按钮
        $('#btnViewDocument').on("click", function () {
            clearMessage();
            page.viewDoc();
        });
        $(document).ready(function () {
            //扫描批次事件
            $('#txtScanContainer').textbox({
                onChange: function (n, o) {
                    page.clearPage(false, true, true, true, true, true);
                    page.pageNumber = 1;
                    page.search();
                }
            });
            //扫描批次事件
            //            $('#txtScanSurPlusEmployeeID').textbox({
            //                onChange: function (n, o) {
            //                    page.clearPage(false, false, false, false, false, true);
            //                    page.bindSurPlusEmployee();
            //                }
            //            });
        });
    },
    //初始化数据
    initData: function () {
        $("#divselfcc").hide(); //自检超差
        $("#divselfbf").hide(); //自检报废
        $("#divchecker").hide(); //检验员
        //        $("#divfirstcheck").hide(); //首件批次号
        //        $("#divviewdoc").hide(); //文档查看
        //        $("#divsurpass").hide(); //超越单
        //        $("#divSurPlusEmployeeID").hide(); //一直隐藏
        page.post(page.url, { action: "InitData" }, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, false);
                return;
            }
            var datas = res.DBDataSet;
            //单位
            $("#UOMField").combobox({
                valueField: 'UOMID',
                textField: 'UOMNAME',
                data: datas.dtUom //下拉数据
            });
            if (datas.dtChecker !== undefined) { //如果是报工选择检验
                $("#divchecker").show();
                //检验员
                $("#ddlChecker").combobox({
                    valueField: 'CHECKERID',
                    textField: 'FULLNAME',
                    data: datas.dtChecker //下拉数据
                });
            }
            if (datas.dtSelf !== undefined) { //如果是自检
                $("#divselfcc").show();
                $("#divselfbf").show();
                $("#divreport").text("自检合格数");
            }
        });
        //        page.search();
    },
    //查询
    search: function () {
        var scanContainer = $.trim($("#txtScanContainer").textbox("getValue"));
        if (scanContainer === "") {
            return;
        }
        var formData = {
            action: "GetRBStepInfoList",
            pageSize: page.pageSize,
            pageIndex: page.pageNumber,
            scanContainer: scanContainer,
            currStep: $("#ckCurrStep").prop("checked")
        };
        page.post(page.url, formData, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, res.Result);
                return;
            }
            page.pageTotal = res.RowCount;
            $("#gdResult").datagrid('loadData', { total: res.RowCount, rows: res.DBTable });
            $("#gdResult").datagrid("selectRow", 0);
        });
    },
    //绑定结余件确认人
    bindSurPlusEmployee: function () {
        page.post(page.url, { action: "GetSurPlusEmployeeInfo", scanSurPlusEmployeeID: $('#txtScanSurPlusEmployeeID').textbox("getValue") }, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, res.Result);
                return;
            }
            if (res.DBTable.length > 0) {
                $("#txtScanSurPlusEmployeeName").textbox("setValue", res.DBTable[0].TXTSCANSURPLUSEMPLOYEENAME);
                $("#lblSurPlusEmployeeID").textbox("setValue", res.DBTable[0].LBLSCANSURPLUSEMPLOYEEID);
            }
        });
    },
    //填充数据
    fillData: function (row) {
        page.clearPage(false, true, true, false, true, true);
        $("#txtProductNO").textbox("setValue", row.PRODUCTNAME); //零件号
        $("#txtProcess").textbox("setValue", row.WORKFLOWSTEPNAME); //当前工序
        $("#txtDispatchQty").textbox("setValue", row.QTY); //派工数
        $("#txtReprotedQty").textbox("setValue", row.DISWORKQTY); //已报数
        $("#txtMaxPriorityCode").textbox("setValue", row.PRIORITYCODE); //最大优先级
        $("#txtReportQty").textbox("setValue", row.CANREPORTQTY); //可报数
        var params = [];
        params.push(row);
        page.post(page.url, { action: "GetFillData", params: JSON.stringify(params) }, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, res.Result);
                return;
            }
            var datas = res.DBDataSet;
            if (datas.dtCollect !== undefined) { //集件列表
                $("#gdCollectInfo").datagrid('loadData', { rows: datas.dtCollect });
            }
            //工序设备
            $("#ddlResource").combobox({
                valueField: 'RESOURCEID',
                textField: 'RESOURCENAME',
                data: datas.dtResource //下拉数据
            });
            if (row.CONTAINERTYPE === 3) {//批量带子序号
                $("#gdChildContainerInfo").datagrid('showColumn', 'SelfCheckLossQty'); //显示自检报废
                $("#gdChildContainerInfo").datagrid('loadData', { rows: datas.dtChild });
            } else if (row.CONTAINERTYPE === 7) //单件单卡
            {
                $("#gdChildContainerInfo").datagrid('showColumn', 'IsFillCheckPoint'); //显示是否录入检测项
                $("#gdChildContainerInfo").datagrid('loadData', { rows: datas.dtSingle });
            }
        });
    },
    //保存报工
    saveWorkReport: function () {
        $('#btnWorkReport').linkbutton('disable'); //禁用按钮
        var resData = page.vaildData();
        if (!resData.result) {
            displayMessage2(resData.msg, false, ["btnWorkReport"]);
            return;
        }
        var formData = {
            action: "SaveStepInfoWorkReportData",
            mainDt: JSON.stringify(resData.mains),
            fillDt: JSON.stringify(resData.datas),
            childDt: JSON.stringify(resData.child)
        };
        page.post(page.url, formData, true, function (res) {
            if (res.Result) {
                page.clearPage(false, true, true, true, true, false);
                page.search();
            }
            displayMessage2(res.Message, res.Result, ["btnWorkReport"]);
        });
    },
    //检测项弹出页面
    openStepCheckItem: function () {
        //打开弹出页面
        var url = getRootPath() + "/forms/Custom/InputCheckItemWorkerPopupForm.aspx?v=" + new Date().getTime();
        window.open(url);
        //        url += "&parentDiv=dg";
        //        $('#dg').dialog({
        //            title: '实测值录入',
        //            width: 1100,
        //            height: 800,
        //            top: 10,
        //            closed: false,
        //            cache: false,
        //            modal: true,
        //            content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
        //            // poPupData: selected, //弹出页面的传参
        //            onClose: function () {
        //                var returnValue = window.returnValue;
        //                if (returnValue != null) {
        //                    if (returnValue.isSuccess == true) {

        //                    }
        //                }
        //            }
        //        });
    },
    //验证填写信息并返回数据
    vaildData: function () {
        var resData = { msg: "", result: true, datas: [], child: [] };
        var row = $("#gdResult").datagrid('getChecked'); //选中的批次
        if (row.length === 0) {
            resData.result = false;
            resData.msg = "未选择报工工步";
            return resData;
        }
        var data = {};
        data.checkType = $("input[name='reportGroup']:checked").val(); //检验类型
        data.reportQty = $("#txtReportQty").textbox("getValue"); //报工数（自检报工便是自检合格数）
        if (isNullOrWhiteSpaceStr(data.reportQty)) {
            data.reportQty = 0;
        }
        data.selfCheckOutofToleranceQty = $("#txtSelfCheckOutofToleranceQty").textbox("getValue"); //自检超差数
        if (isNullOrWhiteSpaceStr(data.selfCheckOutofToleranceQty)) {
            data.selfCheckOutofToleranceQty = 0;
        }
        data.selfCheckLossQty = $("#txtSelfCheckLossQty").textbox("getValue"); //自检报废数
        if (isNullOrWhiteSpaceStr(data.selfCheckLossQty)) {
            data.selfCheckLossQty = 0;
        }
        data.checkerId = $("#ddlChecker").combobox("getValue"); //检验员ID
        data.lblSurPlusEmployeeID = ""; //结余件确认人ID
        data.commentsFirst = $("#txtCommentsFirst").textbox("getValue"); //备注一(数量)
        data.uOMField = $("#UOMField").combobox("getValue"); //备注一(单位)
        data.iNMTQty = ""; //试件数
        data.iNMTLossQty = ""; //试件废票数
        //        if (parseInt(data.iNMTLossQty, 10) > parseInt(row[0].WIPQTY, 10)) {
        //            resData.result = false;
        //            resData.msg = "试件废票数不能大于批次在制数";
        //            return resData;
        //        }
        var valueQty = parseInt(data.reportQty, 10) + parseInt(data.selfCheckOutofToleranceQty, 10) + parseInt(data.selfCheckLossQty, 10);
        //        if (valueQty === 0 && parseInt(data.iNMTQty, 10) === 0) {
        //            resData.result = false;
        //            resData.msg = "不存在试验件,报工数量需大于0。";
        //            return resData;
        //        }

        if (data.checkType === "1" && valueQty !== 1) {
            resData.result = false;
            resData.msg = "首件报工数量只能是1";
            return resData;
        }
        if (valueQty > parseInt(row[0].CANREPORTQTY, 10)) {
            resData.result = false;
            resData.msg = "报工数量不能大于可报数量";
            return resData;
        }
        if (valueQty > parseInt(row[0].WIPQTY, 10)) {
            resData.result = false;
            resData.msg = "报工数量不能大于在制数";
            return resData;
        }
        data.resourceId = $("#ddlResource").combobox("getValue"); //报工设备
        //        data.firstCheckContainer = $("#txtFirstCheckContainer").textbox("getValue"); //首件批次号
        //        data.keyProcessBatchNo = $("#txtKeyProcessBatchNo").textbox("getValue"); //关键过程批次号
        data.notes = $("#txtNotes").textbox("getValue"); //备注
        resData.datas.push(data); //填写的数据
        resData.mains = row; //选择的批次
        if (row[0].CONTAINERTYPE === 7) {//如果是单件单卡，主数据在子批次列表中
            var rows = $("#gdChildContainerInfo").datagrid('getChecked'); //选中的子批次
            if (rows.length === 0) {
                resData.result = false;
                resData.msg = "未选择单件单卡批次";
                return resData;
            }
            if (valueQty !== rows.length) {
                resData.result = false;
                resData.msg = "选择的单件单卡批次与报工数不相等";
                return resData;
            }
            resData.mains = rows;
        } else if (row[0].CONTAINERTYPE === 3) {//如果是批量子序号，则为正常子批次
            var rows = $("#gdChildContainerInfo").datagrid('getChecked'); //选中的子批次
            if (rows.length === 0) {
                resData.result = false;
                resData.msg = "未选择子序号";
                return resData;
            }
            if (valueQty !== rows.length) {
                resData.result = false;
                resData.msg = "选择的零件子序号数量与报工数不相等";
                return resData;
            }
            resData.child = rows;
        }
        return resData;
    },
    //预览批次打印页面 
    viewContainerPrint: function () {
        var selected = $("#gdResult").datagrid("getChecked");
        if (selected.length == 0) {
            displayMessage("请选择批次", false);
            return;
        }
        if (selected[0].CONTAINERTYPE === 7) {
            selected = $("#gdChildContainerInfo").datagrid("getChecked");
            if (selected.length == 0) {
                displayMessage("请选择批次", false);
                return;
            }
        }
        page.post(page.commonUrl, { action: "viewPrintPage", isReBiao: "1", params: JSON.stringify(selected) }, true, function (result) {
            if (!result.Result) {
                displayMessage(result.Message, false);
                return;
            }
            var url = result.ReturnData + "?v=" + new Date().getTime();
            window.open(url);
        });
    },
    //文档查看
    viewDoc: function () {
        var selected = $("#gdResult").datagrid("getChecked");
        if (selected.length == 0) {
            displayMessage("请选择批次", false);
            return;
        }
        if (selected[0].CONTAINERTYPE === 7) {
            selected = $("#gdChildContainerInfo").datagrid("getChecked");
            if (selected.length == 0) {
                displayMessage("请选择批次", false);
                return;
            }
        }
        var url = page.rootPath + '/forms/Custom/' + "ProcessDocumentViewPopupForm.aspx?v=" + new Date().getTime();
        url += "&productId=" + selected[0].PRODUCTID + "&workflowId=" + selected[0].WORKFLOWID;
        $('#dg2').dialog({
            title: '文档查看',
            width: 730,
            height: 590,
            top: 10,
            closed: false,
            cache: false,
            modal: true,
            content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
            onClose: function () {

            }
        });
    },
    //清除页面（查询区域，填写区域，列表区域，是否清空消息）
    clearPage: function (scan, headfill, fill, result, result2, msg) {
        if (scan) {
            $("#txtScanContainer").textbox("clear"); //扫面流水卡
        }
        if (headfill) {
            $("#txtProductNO").textbox("setValue", ""); //零件号
            $("#txtProcess").textbox("setValue", ""); //当前工序
            $("#txtDispatchQty").textbox("setValue", ""); //派工数
            $("#txtReprotedQty").textbox("setValue", ""); //已报数
            $("#txtMaxPriorityCode").textbox("setValue", ""); //最大优先级
        }
        if (fill) {
            $("input[name='radContainerType']").textbox("setValue", ""); //扫面流水卡
            $("#lblSurPlusEmployeeID").textbox("setValue", "");
            $("#txtScanSurPlusEmployeeName").textbox("setValue", "");
            $("#txtReportQty").textbox("setValue", "");
            $("#txtSelfCheckOutofToleranceQty").textbox("setValue", "");
            $("#txtSelfCheckLossQty").textbox("setValue", "");
            $("#ddlChecker").combobox("setValue", "");
            $("#txtCommentsFirst").textbox("setValue", "");
            $("#UOMField").combobox("setValue", "");
            $("#txtINMTQty").textbox("setValue", "");
            $("#txtINMTLossQty").textbox("setValue", "");
            $("#ckCurrStep").prop("checked");
            $("#ddlResource").combobox("setValue", "");
            $("#txtFirstCheckContainer").textbox("setValue", "");
            $("#txtKeyProcessBatchNo").textbox("setValue", "");
            $("#txtNotes").textbox("setValue", "");
        }
        if (result) {
            clearEasyuiDataGrid("gdResult"); //清空结果列表
        }
        if (result2) {
            clearEasyuiDataGrid("gdChildContainerInfo"); //清空子批次列表
            clearEasyuiDataGrid("gdCollectInfo"); //清空集件列表
        }
        if (msg) {
            clearMessage();
        }
    },
    //post数据（路径，参数，是否异步，成功返回方法）
    post: function (url, param, async, callback) {
        $.ajax({
            type: "Post",
            url: url,
            data: param,
            cashe: false,
            async: async,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
                $("body").find(".easyui-linkbutton").each(function () {
                    $(this).linkbutton('enable');
                });
            }
        });
    }
}
page.init();